<?php

namespace App\Http\Controllers;

use App\Models\Config;

class CommonController extends Controller
{
    protected $vars = [];
    //视图访问前缀
    protected $view_prefix = "";

    public function __construct()
    {
        //配置参数共享
        $this->configs = Config::getAllConfig();
        view()->share(['configs' => $this->configs]);
    }

    /**
     * Ajax请求时错误返回json数据
     *
     * @param $message
     * @param $code
     * @param array $data
     * @return \Illuminate\Http\JsonResponse
     */
    protected function error($message, $code = 0, $data = [])
    {
        $result = [
            "code" => $code,
            "message" => $message,
            "data" => $data
        ];
        return response()->json($result);
    }

    /**
     * Ajax请求时成功返回json数据
     *
     * @param $message
     * @param array $data
     * @return \Illuminate\Http\JsonResponse
     */
    protected function success($message, $data = [])
    {
        $result = [
            "code" => 1,
            "message" => $message,
            "data" => $data
        ];
        return response()->json($result);
    }

    /**
     * Ajax请求时成功返回json数据Layui表格
     *
     * @param $message
     * @param array $data
     * @return \Illuminate\Http\JsonResponse
     */
    protected function ajaxData($message, $datas = [])
    {
        $result = [
            "count" => $datas['counts'],
            "data" => $datas['datas'],
            "code" => 0,
            "msg" => $message
        ];
        return response()->json($result);
    }

    /**
     * 给页面变量赋值
     *
     * @param $varname
     * @param $value
     */
    protected function assign($varname, $value)
    {
        $this->vars[$varname] = $value;
    }

    /**
     * 页面输出展示
     *
     * @param $viewname
     * @param array $datas
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    protected function display($viewname = '', $datas = [])
    {
        $viewname = $this->view_prefix . $viewname;
        if (!view()->exists($viewname)) {
            return view("errors." . $this->view_prefix . "404", ['message' => '页面未找到(' . $viewname . ')']);
        } else {
            $conditions = isset($datas['conditions']) ? $datas['conditions'] : [];
            //初始化查询条件参数
            unset($datas['conditions']);
            $datas = array_merge($datas, $conditions);
            $page_datas = array_merge($this->vars, $datas);
            return view($viewname, $page_datas);
        }
    }

    public function __call($method, $parameters)
    {
        parent::__call($method, $parameters); // TODO: Change the autogenerated stub
    }
}
